/**
 * 3η ΓΕ 2013-2014 - Super Market
 * ΦΡΑΓΚΟΥΛΟΠΟΥΛΟΥ ΕΜΜΑΝΟΥΕΛΑ (69298)
 * ΧΑΛΔΑΣ ΧΑΡΑΛΑΜΠΟΣ (69305)
 * ΧΟΡΜΟΒΙΤΗΣ ΙΩΑΝΝΗΣ (69325)
 * ΧΟΥΣΤΟΥΛΑΚΗ ΕΥΑΓΓΕΛΙΑ (69327)
 */
package administratorGUI;

import javax.swing.*;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.YES_NO_OPTION;
import static javax.swing.JOptionPane.YES_OPTION;
import model.*;
import org.jdesktop.beansbinding.Binding;
import supermarket.EntityManagerFactory;

/**
 * Πίνακας Πελατών
 */
public class CustProfileForm extends javax.swing.JInternalFrame {

    /**
     * Constructor
     */
    public CustProfileForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        SuperMarketPUEntityManager = java.beans.Beans.isDesignTime() ? null : EntityManagerFactory.getEntityManager();
        customerQuery = java.beans.Beans.isDesignTime() ? null : SuperMarketPUEntityManager.createQuery("SELECT c FROM Customer c");
        customerList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : customerQuery.getResultList();
        jPanel3 = new javax.swing.JPanel();
        newCustomerButton = new javax.swing.JButton();
        deleteCustomerButton = new javax.swing.JButton();
        processCustomerButton = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        customersTable = new javax.swing.JTable();

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Διαχείριση προφίλ πελατών");
        setToolTipText("");
        setPreferredSize(new java.awt.Dimension(900, 500));

        newCustomerButton.setText("Νέος πελάτης");
        newCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newCustomerButtonActionPerformed(evt);
            }
        });

        deleteCustomerButton.setText("Διαγραφή");
        deleteCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteCustomerButtonActionPerformed(evt);
            }
        });

        processCustomerButton.setText("Επεξεργασία");
        processCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                processCustomerButtonActionPerformed(evt);
            }
        });

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, customerList, customersTable, "CUSTOMER_BIND");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstName}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastName}"));
        columnBinding.setColumnName("Επίθετο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${address}"));
        columnBinding.setColumnName("Διεύθυνση");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${pointsCardNumber}"));
        columnBinding.setColumnName("Κάρτα πόντων");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${password}"));
        columnBinding.setColumnName("Κωδικός");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${creditCardNum}"));
        columnBinding.setColumnName("Πιστωτική κάρτα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane3.setViewportView(customersTable);
        if (customersTable.getColumnModel().getColumnCount() > 0) {
            customersTable.getColumnModel().getColumn(0).setPreferredWidth(50);
            customersTable.getColumnModel().getColumn(4).setPreferredWidth(40);
        }

        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .add(18, 18, 18)
                .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 572, Short.MAX_VALUE)
                .add(18, 18, 18)
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(newCustomerButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(deleteCustomerButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(processCustomerButton, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .add(17, 17, 17))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(jPanel3Layout.createSequentialGroup()
                        .add(newCustomerButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(processCustomerButton)
                        .add(18, 18, 18)
                        .add(deleteCustomerButton)
                        .add(0, 269, Short.MAX_VALUE))))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(4, 4, 4)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rebindCustomersTable() {
        Binding b = bindingGroup.getBinding("CUSTOMER_BIND");
        b.unbind();
        b.bind();
    }


    /**
     * Button: Διαγραφή
     * @param evt 
     */
     private void deleteCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteCustomerButtonActionPerformed
        // Ελέγχω αν υπάρχει επιλεγμένο Row στο Table
        int row = customersTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                     "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }
        Customer customer = customerList.get(row);
        EntityManagerFactory.getEntityManager().refresh(customer);
        
        // Warning  αν ο Πελάτης έχει κάνει Αγορές 
        if (!customer.getPurchaseList().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Ο πελάτης έχει πραγματοποιήσει "
                    + customer.getPurchaseList().size() + " Αγορές.\n"
                    + "Αν επιλέξετε 'Διαγραφή', θα διαγράψετε "
                    + "και τις Αγορές.", "Προσοχή", INFORMATION_MESSAGE);
        }
        
        // Ερώτηση
         if (JOptionPane.showConfirmDialog(this,
                 "Να διαγραφεί η επιλεγμένη εγγραφη;",
                 "Διαγραφή", YES_NO_OPTION) == YES_OPTION) {

             SuperMarketPUEntityManager.getTransaction().begin();
             SuperMarketPUEntityManager.remove(customer);
             SuperMarketPUEntityManager.getTransaction().commit();
             customerList.clear();
             customerList.addAll(customerQuery.getResultList());
             rebindCustomersTable();
             customersTable.updateUI();
         }
     }//GEN-LAST:event_deleteCustomerButtonActionPerformed

     private void newCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newCustomerButtonActionPerformed
         // TODO add your handling code here:
         NewCustomerDialog nc = new NewCustomerDialog(null, true);
         nc.setLocationRelativeTo(this);
         
         nc.setVisible(true);
         if (nc.isValidForSave()) {
            if (nc.isValidForSave()) {
                saveRecord (nc);
             }
         }
     }//GEN-LAST:event_newCustomerButtonActionPerformed

    /**
     * Button: Επεξεργασία
     * @param evt 
     */
     private void processCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processCustomerButtonActionPerformed
        int row = customersTable.getSelectedRow();
        if (row < 0) {
            JOptionPane.showMessageDialog(this, "Δεν έχετε επιλέξει εγγραφή.",
                    "Προσοχή!", INFORMATION_MESSAGE);
            return;
        }

        Customer currentCustomer = customerList.get(row);
        NewCustomerDialog nc = new NewCustomerDialog(null, true);
        nc.setLocationRelativeTo(this);
        nc.setCustomer(currentCustomer);
        nc.setVisible(true);

        if (nc.isValidForSave()) {
            saveRecord(nc, currentCustomer);
        }
     }//GEN-LAST:event_processCustomerButtonActionPerformed

    /**
     * Save Record (mode: Edit Record)
     */
    private void saveRecord (NewCustomerDialog nc, Customer customer) {
        //customer.setCustomerId(customer.getCustomerId());
        customer.setFirstName(nc.getFirstName());
        customer.setLastName(nc.getLastName());
        customer.setAddress(nc.getAddress());
        customer.setPassword(nc.getPassword());
        customer.setCreditCardNum(nc.getCreditCard());
        customer.setBank(nc.getBank());
        customer.setCvv(nc.getCVV());
        customer.setOwner(nc.getHoldersName());
        customer.setPointsCardNumber(nc.getPointsCard());
        SuperMarketPUEntityManager.getTransaction().begin();
        SuperMarketPUEntityManager.merge(customer);
        SuperMarketPUEntityManager.getTransaction().commit();
        customerList.clear();
        customerList.addAll(customerQuery.getResultList());
        rebindCustomersTable();
        customersTable.updateUI();
    }
    
    /**
     * Save Record (mode: New Record)
     */
     private void saveRecord (NewCustomerDialog ns) {
         saveRecord (ns, new Customer());
     }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.persistence.EntityManager SuperMarketPUEntityManager;
    private java.util.List<model.Customer> customerList;
    private javax.persistence.Query customerQuery;
    private javax.swing.JTable customersTable;
    private javax.swing.JButton deleteCustomerButton;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton newCustomerButton;
    private javax.swing.JButton processCustomerButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
}
